package com.lcifn.middleware.rpc.serializer;

import java.io.*;

public class ObjectSerializer implements Serializer {

    @Override
    public byte[] serialize(Object entry) {
        return objectToByte(entry);
    }

    @Override
    public Object deserialize(byte[] bytes, Class clazz) {
        Object obj = null;
        try (ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
             ObjectInputStream ois = new ObjectInputStream(bis);) {

            obj = ois.readObject();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return obj;
    }

    @Override
    public Class getSerializeClass() {
        return Object.class;
    }

    private byte[] objectToByte(Object entry) {
        try (ByteArrayOutputStream bos = new ByteArrayOutputStream();
             ObjectOutputStream oos = new ObjectOutputStream(bos)) {

            oos.writeObject(entry);
            oos.flush();
            return bos.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
